﻿/*
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2010
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
 */

using System;
using DotNetNuke.Security;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.Common;
using DotNetNuke.Entities.Users;

namespace DotNetNuke.UI.Skins.Controls
{

	/// <summary>
	/// 
	/// </summary>
    partial class DNNJDMenu : NavObjectBase
    {

        #region Private Members

        private string _display = "";
        private string _mainarrow = "";
        private string _subarrow = "";
        private string _righttoleft = "";
        private string _separator = "";
        private string _cssname = "jd_menu";
        private string _pagelevel = "0";
        private string _displaychild = "true";
	   readonly TabController _tabcontr = new TabController();

        #endregion

        #region Public Members
         
        public string Url = "0";
        public string JDMenu = "jd_menu";

        #endregion

	   #region Public Properties

	   public string display
        {
            get
            {
                return _display;
            }
            set
            {
                _display = value;
            }
        }

        public string mainarrow
        {
            get
            {
                return _mainarrow;
            }
            set
            {
                _mainarrow = value;
            }
        }

        public string subarrow
        {
            get
            {
                return _subarrow;
            }
            set
            {
                _subarrow = value;
            }
        }

        public string righttoleft
        {
            get
            {
                return _righttoleft;
            }
            set
            {
                _righttoleft = value;
            }
        }

        public string separator
        {
            get
            {
                return _separator;
            }
            set
            {
                _separator = value;
            }
        }

        public string cssname
        {
            get
            {
                return _cssname;
            }
            set
            {
                _cssname = value;
            }
        }

        public string pagelevel
        {
            get
            {
                return _pagelevel;
            }
            set
            {
                _pagelevel = value;
            }
        }

        public string displaychild
        {
            get
            {
                return _displaychild;
            }
            set
            {
                _displaychild = value;
            }
	   }

	   #endregion

	   #region Event Handlers

	    /// <summary>
	    /// Since jdmenu requires jQuery, we register it in DotNetNuke here. 
	    /// </summary>
	    /// <param name="sender"></param>
	    /// <param name="e"></param>
	    protected void Page_Init(Object sender, EventArgs e)
	    {
		   if (Framework.AJAX.IsInstalled())
		   {
		   	Framework.AJAX.RegisterScriptManager();
		   }
	    
		    Framework.jQuery.RequestRegistration();
		}

	    /// <summary>
	    /// This is the part of the life cycle we build the menu and add additional scripts to the page. 
	    /// </summary>
	    /// <param name="sender"></param>
	    /// <param name="e"></param>
	   protected void Page_Load(Object sender, EventArgs e)
        {
             AddScripts();
             JDMenu = cssname;
             ltContent.Text = DefaultRootMenuRead();
        }

#endregion

	   #region Private Methods

	   /// <summary>
	    /// This registers all the scripts necessary to run the skin object. 
	    /// </summary>
	   private void AddScripts() 
	   {
		     Page.ClientScript.RegisterClientScriptInclude("bigframe", TemplateSourceDirectory + "/scripts/jquery.bgiframe.js");
			Page.ClientScript.RegisterClientScriptInclude("dimensions", TemplateSourceDirectory + "/scripts/jquery.dimensions.js");
			Page.ClientScript.RegisterClientScriptInclude("positionBy", TemplateSourceDirectory + "/scripts/jquery.positionBy.js");
	   }

	    /// <summary>
	    /// 
	    /// </summary>
	    /// <returns></returns>
	   private int GetMaxTabOrder() {
		   var maxOrder = 0;
		   var maxTabId = 0;
		   var userinfo = UserController.GetCurrentUserInfo();
		   if (userinfo.IsInRole("Administrators")) {
			   if (userinfo.IsSuperUser) {
				   maxTabId = 7;
			   } else {
				   var tabs = PortalSettings.DesktopTabs;
				   foreach (TabInfo tabinfo in tabs) {
					   if (tabinfo.TabOrder != 10001) continue;
					   maxTabId = tabinfo.TabID;
					   break;
				   }
			   }
		   } else {
			   var tabList = Globals.GetPortalTabs(PortalSettings.DesktopTabs, false, true, false, true);

			   foreach (TabInfo tabinfo in tabList) {
				   if (tabinfo.TabOrder <= maxOrder || tabinfo.ParentId != -1 || tabinfo.IsVisible != true) continue;
				   maxOrder = tabinfo.TabOrder;
				   maxTabId = tabinfo.TabID;
			   }
		   }
		   return maxTabId;

	   }

	    /// <summary>
	    /// 
	    /// </summary>
	    /// <param name="activeTabId"></param>
	    /// <param name="levelParentId"></param>
	    /// <returns></returns>
	   private bool HasParentId(int activeTabId, int levelParentId) {
		   var nowTabId = activeTabId;

		   for (; ; ) {
			   if (nowTabId == levelParentId) {
				   return true;
			   }
			   if (nowTabId == -1) {
				   return false;
			   }
			   nowTabId = _tabcontr.GetTab(nowTabId).ParentId;
			   continue;
		   }
	   }

	    /// <summary>
	    /// 
	    /// </summary>
	    /// <param name="tablevel"></param>
	    /// <param name="parentId"></param>
	    /// <returns></returns>
	   private bool ShowLevel(int tablevel, int parentId) {
		   if (Convert.ToInt32(pagelevel) == 0) {
			   return tablevel == 0;
		   }
		   return tablevel == Convert.ToInt32(pagelevel) && HasParentId(PortalSettings.ActiveTab.TabID, parentId);
	   }

	    /// <summary>
	    /// 
	    /// </summary>
	    /// <param name="currentid"></param>
	    /// <returns></returns>
	   private int ToParentId(int currentid) {
		   var tabController = new TabController();
		   if (tabController.GetTab(currentid).Level > Convert.ToInt32(pagelevel)) {
			   while (tabController.GetTab(currentid).Level != Convert.ToInt32(pagelevel)) {
				   currentid = tabController.GetTab(currentid).ParentId;
			   }
		   }
		   return currentid;
	   }

	    /// <summary>
	    /// This populates a list of tabs and builds the menu line by line (xhtml properyly output ul/li)
	    /// </summary>
	    /// <returns></returns>
	   private string DefaultRootMenuRead() {
		   var OneTab = "";
		   var pageCode = "";

		   // Root
		   for (int intIndex = 0; intIndex < PortalSettings.DesktopTabs.Count; intIndex++) {
			   var objTab = (TabInfo)PortalSettings.DesktopTabs[intIndex];

			   if (objTab.IsVisible && objTab.IsDeleted == false) {
				   if (PortalSecurity.IsInRoles(objTab.AuthorizedRoles)) {
					   if (ShowLevel(objTab.Level, objTab.ParentId)) {
						   var control = 0;
						   var tablist = PortalSettings.DesktopTabs;
						   TabInfo tabinfo;
						   for (var i = 0; i < tablist.Count; i++) {
							   tabinfo = (TabInfo)tablist[i];
							   if (tabinfo.IsVisible && tabinfo.ParentId == objTab.TabID) {
								   control++;
							   }
						   }

						   if (objTab.HasChildren && control != 0) {
							   if (PortalSettings.ActiveTab.TabID == objTab.TabID || objTab.TabID == ToParentId(PortalSettings.ActiveTab.TabID)) {
								   if (objTab.DisableLink == false) {
									   OneTab = objTab.TabID == GetMaxTabOrder() ? string.Format("<li class='haschild activetab'><a href='{0}'><span>{1}" + mainarrow + "</span></a>", objTab.FullUrl, objTab.TabName) : string.Format("<li class='haschild activetab'><a href='{0}'><span>{1}" + mainarrow + separator + "</span></a>", objTab.FullUrl, objTab.TabName);
								   } else {
									   OneTab = objTab.TabID == GetMaxTabOrder() ? string.Format("<li class='haschild activetab'><a><span>{0}" + mainarrow + "</span></a>", objTab.TabName) : string.Format("<li class='haschild activetab'><a><span>{0}" + mainarrow + separator + "</span></a>", objTab.TabName);
								   }
							   } else {
								   if (objTab.DisableLink == false) {
									   OneTab = objTab.TabID == GetMaxTabOrder() ? string.Format("<li class='haschild'><a href='{0}'><span>{1}" + mainarrow + "</span></a>", objTab.FullUrl, objTab.TabName) : string.Format("<li class='haschild'><a href='{0}'><span>{1}" + mainarrow + separator + "</span></a>", objTab.FullUrl, objTab.TabName);
								   } else {
									   OneTab = objTab.TabID == GetMaxTabOrder() ? string.Format("<li class='haschild'><a><span>{0}" + mainarrow + "</span></a>", objTab.TabName) : string.Format("<li class='haschild'><a><span>{0}" + mainarrow + separator + "</span></a>", objTab.TabName);

								   }
							   }
						   } else {
							   if (PortalSettings.ActiveTab.TabID == objTab.TabID || objTab.TabID == ToParentId(PortalSettings.ActiveTab.TabID)) {
								   if (objTab.DisableLink == false) {
									   OneTab = objTab.TabID == GetMaxTabOrder() ? string.Format("<li class='activetab'><a href='{0}'><span>{1}</span></a>", objTab.FullUrl, objTab.TabName) : string.Format("<li class='activetab'><a href='{0}'><span>{1}" + separator + "</span></a>", objTab.FullUrl, objTab.TabName);
								   } else {
									   OneTab = objTab.TabID == GetMaxTabOrder() ? string.Format("<li class='activetab'><a><span>{0}</span></a>", objTab.TabName) : string.Format("<li class='activetab'><a><span>{0}" + separator + "</span></a>", objTab.TabName);
								   }
							   } else {
								   if (objTab.DisableLink == false) {
									   OneTab = objTab.TabID == GetMaxTabOrder() ? string.Format("<li><a href='{0}'><span>{1}</span></a>", objTab.FullUrl, objTab.TabName) : string.Format("<li><a href='{0}'><span>{1}" + separator + "</span></a>", objTab.FullUrl, objTab.TabName);
								   } else {
									   OneTab = objTab.TabID == GetMaxTabOrder() ? string.Format("<li><a><span>{0}</span></a>", objTab.TabName) : string.Format("<li><a><span>{0}" + separator + "</span></a>", objTab.TabName);
								   }
							   }
						   }
						   if (displaychild == "true") {
							   DefaultChildMenuRead(objTab.TabID, ref OneTab);
						   }
						   OneTab += "</li>\n";

						   if (righttoleft == "true") {
							   pageCode = OneTab + pageCode;
						   } else {
							   pageCode += OneTab;
						   }
					   }
				   }
			   }
		   }
		   if (display == "V") {
			   pageCode = "<div class='content' ><ul class='" + cssname + "_vertical " + cssname + "'>" + pageCode + "</ul>\n</div>";
		   } else {
			   pageCode = "<div class='content' ><ul class='" + cssname + " '>" + pageCode + "</ul>\n</div>";
		   }
		   return pageCode;
	   }

	    /// <summary>
	    /// 
	    /// </summary>
	    /// <param name="rootTabId"></param>
	    /// <param name="oneTab"></param>
	   public void DefaultChildMenuRead(int rootTabId, ref string oneTab) {
		   var subCoutHead = 0;

		   for (var childIndex = 0; childIndex < PortalSettings.DesktopTabs.Count; childIndex++) {
			   var childTab = (TabInfo)PortalSettings.DesktopTabs[childIndex];

			   if (!childTab.IsVisible || childTab.IsDeleted) continue;
			   if (PortalSecurity.IsInRoles(childTab.AuthorizedRoles)) {
                       if (childTab.ParentId == rootTabId) {
                            if (subCoutHead == 0) {
						   oneTab += "<ul>";
						   subCoutHead = 1;
					   }
                            var control = 0;
					   var tablist = PortalSettings.DesktopTabs;
					   TabInfo tabinfo;
					   for (var i = 0; i < tablist.Count; i++) {
						   tabinfo = (TabInfo)tablist[i];
						   if (tabinfo.IsVisible && tabinfo.ParentId == childTab.TabID) {
							   control++;
						   }
					   }
                            if (childTab.HasChildren && control != 0) {
						   if (childTab.DisableLink == false) {

							   oneTab += string.Format("<li class='haschild'><a href='{0}'><span>{1}" + subarrow + "</span></a>", childTab.FullUrl, childTab.TabName);
						   } else {
							   oneTab += string.Format("<li class='haschild'><a><span>{0}" + subarrow + "</span></a>", childTab.TabName);
						   }
					   } else {
						   if (childTab.DisableLink == false) {
							   oneTab += string.Format("<li><a href='{0}'><span>{1}</span></a>", childTab.FullUrl, childTab.TabName);
						   } else {
							   oneTab += string.Format("<li><a><span>{0}</span></a>", childTab.TabName);
						   }
					   }
                            DefaultChildMenuRead(childTab.TabID, ref oneTab);
                            oneTab += "</li>\n";
                            }
			   }
		   }
		   if (subCoutHead == 1) {
                  oneTab += "</ul>\n";
		   }
          }

	   #endregion

    }
}